package com.apes.fn.fico.reimbursement.model;

import com.alibaba.fastjson.annotation.JSONField;
import com.apes.crm.business.model.InsuranceCompany;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.Name;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.Arith;
import com.apes.framework.util.DateUtil;
import com.apes.scm.masterdata.finance.model.BankAccount;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.Date;

/**
 * 交易流水
 * Created by lishikun on 2021/1/27 11:21
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicUpdate
@DynamicInsert @Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = TransactionFlow.CONST_TABLE_NAME)
public class TransactionFlow extends Model {
    public static final String CONST_TABLE_NAME = "fn_transaction_flow";

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "交易流水", padding = 7, prefix = "JS")
    @Comment("交易流水编码")
    private String id;

    @Name
    @NonNull
    @Column(name = "transaction_flow_num")
    @Comment("交易流水号")
    private String transactionFlowNum;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "payment_account_id", referencedColumnName = "id")
    @Comment("付款账户")
    private BankAccount bankAccount;

    @NonNull
    @Column(name = "counterparty_account_name")
    @Comment("对方账户")
    private String counterpartyAccountName;

    @NonNull
    @Column(name = "counterparty_account_num")
    @Comment("对方账号")
    private String counterpartyAccountNum;

    @Column(name = "amount", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("付款金额")
    private double amount = 0;

    @Column(name = "used_amount", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("已使用交易额")
    private double usedAmount = 0;

    @Comment("备注")
    @Column(name = "remark", length = 400)
    private String remark;

    @Comment("来源单据")
    @Column(name = "source", length = 30)
    private String source;

    @Comment("来源单据类型")
    @Column(name = "source_business_type", length = 32)
    private String sourceBusinessType;


    @States(name = "银行流水状态", values = {
            @State(id = "create", name = "创建"),
            @State(id = "approve", name = "审核"),
            @State(id = "stop", name = "终止")
    })
    @Column(name = "state", length = 10, nullable = false)
    private String state;

    @Column(name = "use_state", length = 30,columnDefinition = "varchar2(30) default 'unUsed'" )
    @States(name = "银行流水使用状态", values = {
            @State(id = "unUsed", name = "未使用"),
            @State(id = "partialUse", name = "部分使用"),
            @State(id = "fullUse", name = "全额使用")
    })
    private String useState = "unUsed";


    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "approve_date")
    @Comment("审核日期")
    private Date approveDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_id", referencedColumnName = "id")
    @Comment("审核人")
    private PartyRole approveId;

    @Column(name = "car_License",length = 64)
    @Comment("车牌")
    private String carLicense;

    @Comment("部门")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id")
    private Dept dept;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "transaction_date")
    @Comment("交易日期")
    private Date transactionDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "insurance_company_id", referencedColumnName = "id")
    @Comment("保险公司")
    private InsuranceCompany insuranceCompany;

    @Column(name = "receipt_amount", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("收款金额")
    private double receiptAmount = 0;

    @Transient
    private String bankId;

    @Transient
    private String bankName;


    @Transient
    private String accountId;

    @Transient
    private String bankAccountId;


    public String getBankAccountId() {
        if (bankAccount == null) return null;
        return bankAccount.getId();
    }

    public String getBankId() {
        if (bankAccount == null) return null;
        if (bankAccount.getBank() == null) return null;
        return bankAccount.getBank().getId();
    }

    public String getBankName() {
        if (bankAccount == null) return null;
        if (bankAccount.getBank() == null) return null;
        return bankAccount.getBank().getName();
    }

    public String getAccountId() {
        if (bankAccount == null) return null;
        return bankAccount.getAccountId();
    }

    @Transient
    private PartyRole _creator;

    @Transient
    public PartyRole get_creator() {
        if (this.getCreator() == null) return null;
        return SpringManager.getBean(PartyRoleRepository.class).findOne(this.getCreator());
    }


    public void computeAmt(double use) {
        usedAmount += use;
        if (usedAmount > amount) {
            throw new RuntimeException("已使用金额大于交易额！请检查！");
        }
        if (usedAmount == 0) {
            useState = "unUsed";
        } else if (usedAmount == amount) {
            useState = "fullUse";
        } else {
            useState = "partialUse";
        }
    }
}
